<?php 

defined('PHPFOX') or exit('NO DICE!');

class Aecoinbase_Component_Controller_Index extends Phpfox_Component
{
	public function process()
	{
		
		$iUserId = Phpfox::getUserId();
		
		if(!$iUserId || $iUserId == 0 || $iUserId == null){ exit; }
		
		if(!isset($_POST) || !isset($_POST['apikey']) || $_POST['apikey'] == ''){ 
			echo 'Invalid Data';
			exit; 
		}
		
		//If recurring 
		$sRepeat = '';
		if(isset($_POST['repeat'])){ $sRepeat = '"repeat" : "'.$_POST['repeat'].'",'; }
		
		$request = '{
			"api_key" : "'.$_POST['apikey'].'", 
			"button": {
				"type": "'.$_POST['type'].'",
				"name": "'.$_POST['item_name'].'",
				"price_string": "'.$_POST['amount'].'",
				"price_currency_iso": "'.$_POST['currency_code'].'",
				"custom": "'.$_POST['item_number'].'",
				"callback_url": "'.$_POST['notify_url'].'cbsecret_'.Phpfox::getParam('aecoinbase.aecoinbase_secret_key').'/'.'",
				"success_url" : "'.$_POST['return'].'",
				"cancel_url" : "'.$_POST['cancel'].'",
				'.$sRepeat.'
				"auto_redirect" : true
			}
		}';

		$post_fields = json_decode($request, true); //convert json string
		$post_fields = http_build_query($post_fields); 
		
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_TIMEOUT, 10);
		curl_setopt($curl, CURLOPT_POST, true);  
		curl_setopt($curl, CURLOPT_POSTFIELDS, $post_fields); 
		curl_setopt($curl, CURLOPT_URL, 'https://coinbase.com/api/v1/buttons'); 
		
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
		$response = curl_exec($curl);
		
		//response is in json.. decode into an array 
		$aResponse = json_decode($response, true);
		
		// goto: https://aecoinbase.com/checkouts/CODE   CODE being the 'code' parameter returned by the api response 
		if(!isset($aResponse['success']) || $aResponse['success'] != true){	
			die("Coinbase Invoice Error");
		}else{
			header("Location: https://coinbase.com/checkouts/".$aResponse['button']['code']); 
		}
		exit;
		
	}
	
}

?>